namespace GYLite
{
    export class SeqURLLoader extends egret.EventDispatcher
	{
		private _loadInfo:LoadInfo;
		private _intervalId:number;
		private _isLoading:number;		
		public data:any;
		private _cancelLockTime:number;
		public progressData:any;
		private _laterFunc:Function;
		private _laterObject:any;		
		private _loaderFactory:LoaderFactory;
		public constructor()
		{
			super();
			let s = this;
			s._loadInfo=null;
			s._intervalId=-1;
			s._isLoading=0;			
			s.data=null;
		}
		public set loadInfo(val:LoadInfo)
		{
			let s = this;
			if(val == null)
			{
				s._isLoading=0;
				if(s._cancelLockTime == 0)
					s.clearCallLater();				
				s.data = null;//清空数据放置内存滞留				
				s.progressData = null;
				s.release();
			}
			s._loadInfo = val;
		}
		public get loadInfo():LoadInfo
		{
			return this._loadInfo;
		}
		public handleEvent(e:any):void
        {
			let s = this;
			if(GYLoader._disposed)return;
			s.progressData = e;
			s.dispatchEventWith("progress");
		}
		public close():void
		{
			let s = this;
			s.release();
		}
		public load(req:URLRequest):void
		{
			let s =this;
			if(GYLoader._disposed)return;
			s.release();
			s._loaderFactory = new LoaderFactory;        
			s._loaderFactory.loadData(req, s.loadInfo.type, s.loadComp, s, s.handleEvent.bind(s));
		}	
		private loadComp(status:number)
		{
			if(GYLoader._disposed)return;
			let s = this;
			if(status != 0 && status != 200)
			{
				s.loadError();
				return;
			}
			s.dispatchEvent(new egret.Event(egret.Event.COMPLETE));
		}
		private loadError():void{
			if(GYLoader._disposed)return;
			let s = this;
			s.data = null
			s.dispatchEvent(new egret.IOErrorEvent(egret.IOErrorEvent.IO_ERROR));
		}	
		private release():void
		{
			let s = this;
			if(s._loaderFactory)
			{
				s._loaderFactory.dispose();
            	s._loaderFactory = null;
			}			
		}
		
		/**由于连续加载时，上一个失败立即使用这个loader会产生加载中断的bug，所以进行延时处理*/
		public callLater(func:Function,thisObject:any,delay:number=100)
		{
			let s = this;
			s._laterFunc = func;
			s._laterObject = thisObject;
			func = func.bind(thisObject);
			s._intervalId = setTimeout(s.laterCall.bind(s),delay);
		}
		private laterCall():void
		{
			let s= this;
			if(s._laterFunc!=null)
			{
				s._laterFunc.call(s._laterObject,s);
				s._laterFunc = s._laterObject = null;
			}
				
		}
		/**清理延时*/
		public clearCallLater():void
		{
			let s = this;
			if(s._intervalId > -1)
			{
				clearInterval(s._intervalId);
				s._intervalId = -1;
			}
		}
		public get cancelLockTime():number
		{
			return this._cancelLockTime;
		}
		public set cancelLockTime(value:number)
		{
			this._cancelLockTime = value;
		}
		public get isLoading():number
		{
			return this._isLoading;
		}
		public set isLoading(val:number)
		{
			this._isLoading = val;
		}
		public breakLock()
		{
            let s = this;
			s._cancelLockTime = 0;
		}		
	}	
}